package com.myapp.ruyixing.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.FoodList;
import com.myapp.ruyixing.model.FoodList.Food;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.BitmapLruCache;

public class FoodListActivity extends BaseActivity implements OnClickListener,
		OnItemClickListener {

	private FoodListAdapter mListAdapter;
	private List<Food> mData;
	private ListView mListView;
	private View mEmptyView;

	private View mMenuLayout;

	private TextView mDistanceTabView;
	private TextView mTypeTabView;
	private TextView mOrderTabView;

	private MenuState mMenuState = MenuState.NONE;

	private String mActiveDistance;
	private String mActiveType;
	private String mActiveOrder;

	private DistanceMenuFragment mDistanceMenuFragment;
	private OrderMenuFragment mOrderMenuFragment;
	private FoodTypeFragment mFoodTypeMenuFragment;

	private enum MenuState {
		NONE, DISTANCE, TYPE, ORDER
	}

	private RYHttpResponseHandler mHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			FoodList data = (FoodList) o;
			mData.clear();
			if (data != null && data.list != null) {
				mData.addAll(data.list);
			}

			mListAdapter.notifyDataSetChanged();
			mListView.setEmptyView(mEmptyView);
			((TitleBar) findViewById(R.id.title_bar)).showLoading(false);
		}

		@Override
		public void onFailure(Throwable throwable) {
			((TitleBar) findViewById(R.id.title_bar)).showLoading(false);

			if (!isFinishing()) {
				Toast.makeText(getApplicationContext(), "加载失败",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_food_list);

		mActiveDistance = "500";
		mActiveOrder = "default";
		mActiveType = "food";

		initViews();

		loadData();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		RYHttpClient.cancleRequest(this);
	}

	private void initViews() {
		mListView = (ListView) findViewById(android.R.id.list);
		mEmptyView = findViewById(android.R.id.empty);
		mData = new ArrayList<Food>();
		mListAdapter = new FoodListAdapter(mData);
		mListView.setAdapter(mListAdapter);
		mListView.setOnItemClickListener(this);

		mDistanceTabView = (TextView) findViewById(R.id.distance);
		mTypeTabView = (TextView) findViewById(R.id.type);
		mOrderTabView = (TextView) findViewById(R.id.order);

		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(this);

		mMenuLayout = findViewById(R.id.menus);

		mDistanceTabView.setOnClickListener(this);
		mTypeTabView.setOnClickListener(this);
		mOrderTabView.setOnClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (position >= 0 && position < mData.size()) {
			Food item = mData.get(position);
			FoodDetailActivity.startFoodDetailActivity(this, item.id);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_icon:
			finish();

			break;
		case R.id.distance:
			if (mMenuState == MenuState.DISTANCE) {
				closeMenu();
			} else {
				mMenuLayout.setVisibility(View.VISIBLE);
				if (mDistanceMenuFragment == null) {
					mDistanceMenuFragment = new DistanceMenuFragment();
				}
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.menus, mDistanceMenuFragment).commit();
				mMenuState = MenuState.DISTANCE;
			}

			break;

		case R.id.type:
			if (mMenuState == MenuState.TYPE) {
				closeMenu();
			} else {
				mMenuLayout.setVisibility(View.VISIBLE);
				if (mFoodTypeMenuFragment == null) {
					mFoodTypeMenuFragment = new FoodTypeFragment();
				}
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.menus, mFoodTypeMenuFragment).commit();
				mMenuState = MenuState.TYPE;
			}

			break;

		case R.id.order:
			if (mMenuState == MenuState.ORDER) {
				closeMenu();
			} else {
				mMenuLayout.setVisibility(View.VISIBLE);
				if (mOrderMenuFragment == null) {
					mOrderMenuFragment = OrderMenuFragment
							.newOrderMenuFragment(true);
				}
				getSupportFragmentManager().beginTransaction()
						.replace(R.id.menus, mOrderMenuFragment).commit();
				mMenuState = MenuState.ORDER;
			}

			break;
		case R.id.signup:
			Toast.makeText(this, "报名成功", Toast.LENGTH_LONG).show();

			break;

		default:
			break;
		}
	}

	public void changeType(String typeid, String name) {
		if (!mActiveType.equals(typeid)) {
			mActiveType = typeid;
			mTypeTabView.setText(name);

			loadData();
		}

		closeMenu();
	}

	public void changeDistance(String distance, String newWord) {
		if (!mActiveDistance.equals(distance)) {
			mActiveDistance = distance;
			mDistanceTabView.setText(newWord);

			loadData();
		}

		closeMenu();
	}

	public void changeOrder(String order, String newWord) {
		if (!mActiveOrder.equals(order)) {
			mActiveOrder = order;
			mOrderTabView.setText(newWord);

			loadData();
		}

		closeMenu();

	}

	private void closeMenu() {
		mMenuLayout.setVisibility(View.GONE);
		mMenuState = MenuState.NONE;
		android.support.v4.app.Fragment fragment = getSupportFragmentManager()
				.findFragmentById(R.id.menus);
		if (fragment != null) {
			getSupportFragmentManager().beginTransaction().remove(fragment)
					.commit();
		}
	}

	private void loadData() {
		((TitleBar) findViewById(R.id.title_bar)).showLoading(true);
		RYHttpClient.getFoodListV2(this, mHandler, mActiveType, mActiveOrder,
				mActiveDistance);
	}

	private class FoodListAdapter extends ArrayAdapter<Food> {

		private class ViewHolder {
			public TextView mFoodName;
			public TextView mAddressView;
			public TextView mRecommend;
			public NetworkImageView mFoodImage;
			public TextView mPriceView;
			public TextView mDistanceView;
		}

		private RequestQueue mQueue;
		private ImageLoader mImageLoader;

		public FoodListAdapter(List<Food> data) {
			super(FoodListActivity.this, -1, data);
			mQueue = Volley.newRequestQueue(FoodListActivity.this);
			mImageLoader = new ImageLoader(mQueue, new BitmapLruCache());
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			Food food = (Food) getItem(position);
			if (food == null) {
				return convertView;
			}
			if (convertView == null) {
				convertView = LayoutInflater.from(FoodListActivity.this)
						.inflate(R.layout.food_list_item, parent, false);
				holder = new ViewHolder();
				holder.mAddressView = (TextView) convertView
						.findViewById(R.id.text_address);
				holder.mFoodImage = (NetworkImageView) convertView
						.findViewById(R.id.img_food);
				holder.mFoodName = (TextView) convertView
						.findViewById(R.id.text_food_name);
				holder.mRecommend = (TextView) convertView
						.findViewById(R.id.text_recommend);
				holder.mDistanceView = (TextView) convertView
						.findViewById(R.id.distance);
				holder.mPriceView = (TextView) convertView
						.findViewById(R.id.text_price);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (!TextUtils.isEmpty(food.address)) {
				holder.mAddressView.setText("地址：" + food.address);
			} else {
				holder.mAddressView.setText("地址：");
			}

			holder.mFoodName.setText(food.name);

			holder.mFoodImage.setImageUrl(food.picurl, mImageLoader);

			if (!TextUtils.isEmpty(food.desc)) {
				holder.mRecommend.setText("推荐理由：" + food.desc);
			} else {
				holder.mRecommend.setText("推荐理由：");
			}

			if (!TextUtils.isEmpty(food.price)) {
				holder.mPriceView.setText("价格：¥" + food.price);
			} else {
				holder.mPriceView.setText("价格：");
			}

			long sDistance = food.distance;
			if (sDistance >= 0) {
				String distance = "";
				if (sDistance >= 1000) {
					if (sDistance >= 1000000) {
						distance = "999+km";
					} else {
						distance = String.format("%.1fkm",
								((double) sDistance) / 1000);
					}
				} else {
					distance = sDistance + "m";
				}
				holder.mDistanceView.setText(distance);
			}

			return convertView;
		}
	}

}
